//
//  NSString+Extension.m
//  QQ聊天布局
//
//  Created by TianGe-ios on 14-8-20.
//  Copyright (c) 2014年 TianGe-ios. All rights reserved.
//

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com

#import "NSString+Extension.h"
//#import "SVProgressHUD.h"

@implementation NSString (Extension)

- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

- (CGSize)sizeWithFont:(UIFont *)font
{
    [self sizeWithFont:font constrainedToSize:CGSizeMake(0, 0) lineBreakMode:NSLineBreakByWordWrapping];
    return [self sizeWithFont:font maxW:MAXFLOAT];
}


#pragma mark 清空字符串中的空白字符
- (NSString *)trimString
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

#pragma mark 是否空字符串
- (BOOL)isEmptyString
{
    return (self.length == 0);
}

#pragma mark 返回沙盒中的文件路径
/**
 *  沙盒全路径
 *
 *  @return 返回沙盒全路径
 */
- (NSString *)documentsPath
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    return [path stringByAppendingPathComponent:self];
}


/**
 *  沙盒全路径
 *
 *  @return 返回沙盒全路径
 */
- (NSString *)temp
{
    NSString *path =NSTemporaryDirectory();
    return [path stringByAppendingPathComponent:self];
}

#pragma mark 写入系统偏好
- (void)saveToNSDefaultsWithKey:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] setObject:self forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


+(NSString *)stringFromNSDefaultsWithKey:(NSString *)key
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:key];
}


- (NSString *)firstCharactor
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:self];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}


- (NSString *) pinyinStr {
    NSMutableString *source = [self mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pinYin = [source capitalizedString];
    return pinYin;
}



//177号码 当做不是手机号
//- (BOOL)telString
//{
//    
//    
//    
//    //1[0-9]{10}
//    
//    //^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$
//    
//    //    NSString *regex = @"[0-9]{11}";
//    
//    NSString *regex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
//    
//    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
//    
//    BOOL isMatch = [pred evaluateWithObject:self];
//    
//    if (!isMatch) {
//        
//        //        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入正确的手机号码" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        //
//        //        [alert show];
//
//        
//        
//        
//        return NO;
//        
//    }
//    return YES;
//}

-(void)showHUD
{
  
    if (![self length]) {
        return;
    }
    
    MBProgressHUD *hud = nil;

//     NSLog(@"xxx  字符串%@",[[UIApplication sharedApplication].windows lastObject]);
        hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].windows lastObject] animated:YES];

    // Configure for text only and offset down
    hud.animationType = MBProgressHUDAnimationZoomOut;
    hud.mode = MBProgressHUDModeText;
    hud.userInteractionEnabled = NO;
    hud.labelText = self ;//
    //              hud.labelText =  @"无法连接到服务器，请检查网络设置";
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:1.8];
    

}


-(void)showHUDToView:(UIView *)view
{
    
    if ([self length] == 0) {
        return;
    }
//    NSLog(@"xxx  字符串%@",[[UIApplication sharedApplication].windows lastObject]);
    MBProgressHUD *hud = nil;
    
    hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    
    // Configure for text only and offset down
    hud.animationType = MBProgressHUDAnimationZoomOut;
    hud.mode = MBProgressHUDModeText;
    hud.userInteractionEnabled = NO;
    hud.labelText = self ;//
    //              hud.labelText =  @"无法连接到服务器，请检查网络设置";
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:2];
    
    
}

-(void)showHUD:(NSInteger)time
{
    if ([self length] == 0) {
        return;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo: [[UIApplication sharedApplication].windows lastObject] animated:YES];

//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].windows lastObject]  animated:YES];
    //            MBProgressHUD *hud = [[MBProgressHUD alloc] initWithWindow:weakself.window];
    
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.labelText = self ;//
    //              hud.labelText =  @"无法连接到服务器，请检查网络设置";
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:time];
    
    
}

#pragma mark -是否包含字符串ios8之前版本使用
- (BOOL)ContainsStringIOS7:(NSString*)other {
    NSRange range = [self rangeOfString:other];
    return range.length != 0;
}



-(BOOL)isOnlyNumber{
    NSError *error = nil;

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[1-9]\\d*$" options:NSRegularExpressionCaseInsensitive error:&error];
    NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
    if (result) {
        return YES;
    }else{
        return NO;
    }
}

- (BOOL)isOnlyZhongWenOrZMSZ{
    
    //发送前先检查输入内容
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z0-9\u4e00-\u9fa5]+$" options:NSRegularExpressionCaseInsensitive error:&error];
    NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
    if (result) {
        return YES;
    }else{
        return NO;
    }
}



- (NSString *)pinyinStr2
{
    NSMutableString *pinyin = [self mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
//    NSLog(@"%@", pinyin);
    return [pinyin stringByReplacingOccurrencesOfString:@" " withString:@""].lowercaseString;
}



-(void)showAlert

{
//    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:self message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//    [alert show];
    [self showHUD];

}


/**
 *  生成时间戳
 *
 *  @return 时间戳
 */
+ (NSString *)timeSp
{
    
    
    
    NSTimeInterval  time =[[NSDate date] timeIntervalSince1970];
    return [NSString stringWithFormat:@"%ld",(long)time ];
//    NSDate *datenow = [NSDate date];
//    NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
//    NSInteger interval = [zone secondsFromGMTForDate:datenow];
//    NSDate *localeDate = [datenow  dateByAddingTimeInterval: interval];
//    NSString *timeSp = [NSString stringWithFormat:@"%d", [localeDate timeIntervalSince1970]];
//    return timeSp;
}



-(NSMutableAttributedString *)lineString{
    NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:
                              
                              
                              [NSNumber numberWithInteger:NSUnderlineStyleSingle],   NSStrikethroughStyleAttributeName, nil];
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self     attributes:attrDict];
    return  attrStr;
}



-(BOOL)zhengze:(NSString *)strZhengze
{
    
        NSError *error = nil;
        
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:strZhengze options:NSRegularExpressionCaseInsensitive error:&error];
        NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
        if (result) {
            return YES;
        }else{
            return NO;
        }
    
}

@end
